/**
 * @file mystring.cc
 * @author your name (you@domain.com)
 * @brief
 * @version 0.1
 * @date 2022-03-26
 *
 * @copyright Copyright (c) 2022
 *
 */

#include <iostream>
#include <string.h>

using namespace std;

class MyString
{
  public:
    MyString() // 无参构造，生成一个空串
        : _pstr(new char()), _length(0)
    {
        cout << "MyString() 无参构造" << endl;
        strcpy(_pstr, "");
    }
    ~MyString()
    {
        cout << "~MyString() 析构" << endl;
        if (_pstr) {
            delete[] _pstr;
        }
    }
    MyString(const char *pstr)
        : _pstr(new char[strlen(pstr) + 1]()), _length(strlen(pstr))
    {
        cout << "MyString(const char *) 有参构造" << endl;
        strcpy(_pstr, pstr);
    }
    MyString(const MyString &rhs)
        : _pstr(new char[strlen(rhs._pstr) + 1]()), _length(strlen(rhs._pstr))
    {
        cout << "MyString(const MyString&) 有参构造" << endl;
        strcpy(_pstr, rhs._pstr);
    }
    MyString(size_t count, const char ch)
        : _pstr(new char[count + 1]()), _length(count)
    {
        cout << "MyString(size_t, const char) 有参构造" << endl;
        for (int i = 0; i < count; ++i) {
            _pstr[i] = ch;
        }
    }
    MyString &operator=(const char *pstr)
    {
        cout << "MyString &operator=(const char *)赋值控制 (回收左操作数，深拷贝)" << endl;
        if (_pstr) {
            delete[] _pstr;
        }
        _pstr = new char[strlen(pstr) + 1]();
        _length = strlen(pstr);
        strcpy(_pstr, pstr);
        return *this;
    }
    MyString &operator=(const MyString &rhs)
    {
        cout << "MyString &operator=(const MyString&)赋值控制 (自复制，回收左操作数，深拷贝)" << endl;
        if (this != &rhs) {
            if (_pstr) {
                delete[] _pstr;
            }
            _pstr = new char[strlen(rhs._pstr) + 1]();
            _length = strlen(rhs._pstr);
            strcpy(_pstr, rhs._pstr);
        }
        return *this;
    }

    size_t size() const { return _length; }
    size_t length() const { return _length; }

  private:
    char *_pstr;
    size_t _length;
};

void test0()
{
    MyString s1;
    MyString s2("I am s2");
    MyString s3(s2);
    MyString s4(4, 's');
    s1 = "I am s1";
    s2 = s1;
}

int main()
{
    test0();
    return 0;
}